import { localMenuList, MenuItem } from '@/routes/localMenuList'
import { localRouteList, routeWhiteList } from '@/routes/localRouteList'
import { arrayFlat } from '@/utils'
import { ActionReducerMapBuilder, createSlice } from '@reduxjs/toolkit'
import { RouteObject } from 'react-router-dom'
import { getMenuListAction } from '../actions/global.action'

export type GlobalInitialState = {
    menuList: any[] // 服务端菜单列表
    authMenuList: MenuItem[] // 菜单列表
    authMenuTreeList: MenuItem[] // 菜单树形列表
    authGrainList: any[] // 颗粒/按钮权限列表
    authRouteList: RouteObject[] // 路由列表
    authRouteTreeList: RouteObject[] // 路由树形列表
}

// 初始状态
const initialState: GlobalInitialState = {
    menuList: [],
    authMenuList: [],
    authMenuTreeList: [],
    authGrainList: [],
    authRouteList: [],
    authRouteTreeList: [],
}

// 全局状态
export default createSlice({
    name: 'global',
    initialState,
    reducers: {},
    extraReducers: (builder) => {
        setAuthList(builder)
    },
})

// 设置（菜单和路由）权限
function setAuthList(builder: ActionReducerMapBuilder<GlobalInitialState>) {
    builder.addCase(getMenuListAction.fulfilled, (state, { payload }) => {
        const dataList = payload as unknown as any[]
        state.menuList = dataList.filter((item) => item.pagepermission != 3 && item.showMenu)
        state.authGrainList = dataList.filter((item) => item.pagepermission === 3)
        const menus = generateMenuList(state.menuList, localMenuList)
        const routes = generateRouteList(state.menuList, localRouteList)
        state.authMenuList = arrayFlat(menus)
        state.authMenuTreeList = menusToAntdMenus(menus)
        state.authRouteList = arrayFlat(routes)
        state.authRouteTreeList = routes
    })
    builder.addCase(getMenuListAction.rejected, () => {
        console.error('fail: getMenuListAction')
    })
}

// 将菜单转换成antd的菜单格式
function menusToAntdMenus(menus: MenuItem[]) {
    let result: MenuItem[] = []
    menus.forEach((item) => {
        if (!item.hideSideMenu) {
            delete item.hideSideMenu
            delete item.isRightControl
            result.push(item)
        }
        if (item?.children?.length) {
            item.children = menusToAntdMenus(item.children)
        } else {
            delete item.children
        }
    })

    return result
}

// 生成菜单表
function generateMenuList(authList: any[], localMenuList: MenuItem[]): MenuItem[] {
    let result: MenuItem[] = []
    localMenuList.forEach((item, idx) => {
        const newItem = {...item}
        if (item.isRightControl) {
            authList.findIndex((authItem) => authItem.title === newItem.label) !== -1 && result.push(newItem)
        } else {
            result.push(newItem)
        }
        if (newItem?.children) {
            newItem.children = generateMenuList(authList, newItem?.children!)
        }
    })

    return result
}

// 生成路由表
function generateRouteList(authList: any[], localRouteList: RouteObject[]): RouteObject[] {
    let result: RouteObject[] = []
    localRouteList.forEach((item, idx: number) => {
        const newItem = {...item}
        const index = authList.findIndex((authItem) => authItem.path === newItem.path)
        if (routeWhiteList.includes(newItem.path!) || index !== -1) {
            result.push(newItem)
        }
        if (newItem?.children) {
            newItem.children = generateRouteList(authList, newItem?.children!)
        }
    })

    return result
}
